// 云函数入口文件
const cloud = require('wx-server-sdk')

// 错误码
const ERROR_CODE = {
  NOT_FOUND: 10001,  // 画板不存在
  NOT_MEMBER: 10002, // 不是画板的成员
  PAREM_EMPTY: 10003, // 参数为空
  NOT_EDIT_AUTH: 10004, // 没有编辑权限
}

function dateFormat(date) {
  return date.toJSON().substr(0, 19).replace('T', ' ');;
}

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { drawBoardId, imgId } = event;

  if (!imgId) {
    return {
      data: {},
      code: ERROR_CODE.PAREM_EMPTY,
      msg: '参数为空'
    }
  }

  try {
    // 根据 id 获取当前画板信息
    const drawBoardDatas = await db.collection('drawBoards').where({
      _id: drawBoardId
    }).get();

    // 画板不存在
    if (!drawBoardDatas.data.length) {
      return {
        data: {},
        code: ERROR_CODE.NOT_FOUND,
        msg: '画板不存在'
      }
    }

    const drawBoardData = drawBoardDatas.data[0];
    const { members, owner } = drawBoardData;
    const userInfo = members[OPENID];
    // 不是当前画板的成员
    if (!userInfo) {
      return {
        data: owner,
        code: ERROR_CODE.NOT_MEMBER,
        msg: 'user not member'
      }
    }

    // 没有编辑权限
    if (userInfo.auth !== 'edit') {
      return {
        data: owner,
        code: ERROR_CODE.NOT_EDIT_AUTH,
        msg: 'user not edit anth'
      }
    }

    // 修改当前标题
    await db.collection('drawBoards').where({
      _id: drawBoardId
    }).update({
      data: {
        imgId,
        updateDate: dateFormat(new Date(Date.now() + 8 * 60 * 60 * 1000)),
      }
    })
    return {
      data: {},
      code: 0,
      msg: 'success'
    }
  } catch (err) {
    return {
      code: 1,
      msg: err,
      data: {}
    }
  }
}